<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    public function cards()
    {
        return $this->hasMany('\App\Card')->orderBy('created_at','desc');
    }

    //用户的文章列表
    public function posts()
    {
        return $this->hasMany('\App\Post','user_id','id');
    }

    //关注我的fan模型
    public function fans()
    {
        //parameter1 关联对象 parameter2 关联对象的外键 parameter3 本模型主键
        return $this->hasMany(\App\Fan::class, 'star_id', 'id');
    }

    //我关注的fan模型
    public function stars()
    {
        //parameter1 关联对象 parameter2 关联对象的外键 parameter3 本模型主键
        return $this->hasMany(\App\Fan::class, 'fan_id', 'id');
    }

    //关注某人
    public function doFan($uid=0)
    {
        //parameter1 关联对象 parameter2 关联对象的外键 parameter3 本模型主键
        $fan = new \App\Fan();
        $fan->star_id = $uid;
        $fan->fan_id = \Auth::id();
        return $fan->save();
    }

    //取消关注
    public function doUnfan($uid=0)
    {
        //parameter1 关联对象 parameter2 关联对象的外键 parameter3 本模型主键
        $fan = new \App\Fan();
        $star_id = $uid;
        $fan_id = \Auth::id();
        return $fan->where(compact('star_id','fan_id'))->delete();
    }

    //当前用户是否被uid关注了
    public function hasFan($uid)
    {
        return $this->fan()->where('fan_id',$uid)->count();
    }

    //当前用户是否关注了uid
    public function hasStar($uid)
    {
        return $this->stars()->where('fan_id',$uid)->count();
    }

}
